/**
 * @file usr_event_handler.c
 * @author zcj (605607217@qq.com)
 * @brief
 * @version ecu-中控
 * @date 2023-11-06
 *
 * @copyright Copyright (c) 2023
 *
 */

#include "main.h"

luat_rtos_task_handle message_event_deal_task_handle;
luat_rtos_task_handle wheel_event_deal_task_handle;
luat_rtos_task_handle gps_event_deal_task_handle;
luat_rtos_task_handle ota_event_deal_task_handle;
luat_rtos_task_handle sleep_event_deal_task_handle;
luat_rtos_task_handle publish_task_handle;
//extern WORK_LED_CTRL_T gsm_work_led;
extern EBIKE_STATE_T g_ebike_status;
BEEP_PLAY_T beep_player;
/**
 * @brief wheel event deal
 *
 * @param param
 * @author zcj (605607217@qq.com)
 * @date 2023-11-06
 */
static void wheel_event_deal_task(void *param)
{
    int wheel_status = 1;
    bool wheel_flag=false;
    bool one_flag=false;
    uint8_t wheel_count=0;
    while (1)
    {
        /*1.检测有无轮动信号*/
        if ((get_ebike_state_info(&g_ebike_status, WORK_STATUS) != V_SLEEP))//非休眠模式，才去检测轮动。
        {
            wheel_status = wheel_status_check();
            if (wheel_status==0)//有轮动
            {
                if(wheel_count++>5)
                {
                    wheel_count=0;
                    wheel_flag=true;
                    one_flag=false;
                }
            }
            else
            {
                wheel_count=0;
                wheel_flag=false;
            }
            
            /*2.有*/
            if (wheel_flag==true)
            {
                /**设置轮动标志位 ON*/
                if ((get_ebike_state_info(&g_ebike_status, MOVE_FLAG) != V_ON)&&(get_ebike_state_info(&g_ebike_status, WORK_STATUS) != V_MOVE))
                {
                    set_ebike_state_info(&g_ebike_status, MOVE_FLAG, V_ON);
                    set_ebike_state_info(&g_ebike_status,WORK_STATUS,V_MOVE);//运动状态
                    set_ebike_rules(&g_ebike_status,EBIKE_STATUS);//车辆发生了改变
                }         
            // usr_log("MOVE_FLAG>>>>V_ON");
                /*根据条件判断是否触发轮动报警*/
                if (get_ebike_state_info(&g_ebike_status, BIKE_LOCKED) == V_ON &&
                    get_ebike_state_info(&g_ebike_status, ANTI_THEFT) == V_OFF &&
                    get_ebike_state_info(&g_ebike_status, ACC_STATUS) != V_ON)
                {
                    set_ebike_state_info(&g_ebike_status, ANTI_THEFT, V_ON);
                    luat_rtos_message_send(message_event_deal_task_handle, CASE_TASK_ON_ALARM, (void *)NULL);
                }           
            }
            /*3.没有*/
            else
            {
                /*设置轮动标志位 OFF*/
                if ((get_ebike_state_info(&g_ebike_status, MOVE_FLAG) != V_OFF)&&(get_ebike_state_info(&g_ebike_status, WORK_STATUS) != V_STOP))
                {
                    set_ebike_state_info(&g_ebike_status, MOVE_FLAG, V_OFF);
                    set_ebike_state_info(&g_ebike_status,WORK_STATUS,V_STOP);//静止状态
                    set_ebike_rules(&g_ebike_status,EBIKE_STATUS);//车辆发生了改变
                }
                // usr_log("MOVE_FLAG>>>>V_OFF");
            }
            usr_delay_ms(200);
        }
    }
}

/**
 * @brief sleep event deal
 *  1.还车状态下==> 超过十分钟&不触发轮动 &未收到mqtt消息 ==>进入低功耗
 *  2.低功耗下1小时退出更新硬件参数,30秒后再次进入
 * @param pv
 * @author zcj (605607217@qq.com)
 * @date 2023-11-06
 */
void sleep_event_deal_task(void *pv)
{
    low_power_init();
   // luat_pm_wakeup_pad_set_callback(low_power_wakeup_callback);
    while (1)
    {
        /**
         * 借车状态，持续清零，不进入低功耗计时
         */
        if (get_ebike_state_info(&g_ebike_status, WORK_STATUS) == V_MOVE)
        {
            clear_sleep_count(&g_ebike_status.sleep);
        }

        /**
         * 非骑行状态进入低功耗策略，5分钟
         */
        else if (get_ebike_state_info(&g_ebike_status, WORK_STATUS) == V_STOP)
        {
            sleep_in_count_add(&g_ebike_status.sleep);
            if (get_sleep_in_count(&g_ebike_status.sleep) >= NO_WORK_ENTRE_LOW_POWER_TIME)
            {                
                if ((get_ebike_state_info(&g_ebike_status, WORK_STATUS) != V_SLEEP))
                {
                    set_ebike_state_info(&g_ebike_status,WORK_STATUS,V_SLEEP);//进入低功耗状态
                    set_ebike_rules(&g_ebike_status,EBIKE_STATUS);
                    usr_enter_low_power();//
                }                
            }
        }

        /**
         * 轮动报警退出低功耗
         */
        if (get_pre_quit_flag(&g_ebike_status.sleep) == true && get_ebike_state_info(&g_ebike_status, WORK_STATUS) == V_SLEEP)
        {
            if ((get_ebike_state_info(&g_ebike_status, WORK_STATUS) != V_STOP))
            {
                usr_quit_low_power();
                set_ebike_state_info(&g_ebike_status,WORK_STATUS,V_STOP);//退出低功耗状态
                set_ebike_rules(&g_ebike_status,EBIKE_STATUS);
                set_pre_quit_flag(&g_ebike_status.sleep, false);
            }
        }

        /**
         * 低功耗下每1小时退出低功耗，更新（大/小）电池电压
         */
        if (get_ebike_state_info(&g_ebike_status, WORK_STATUS) == V_SLEEP)
        {
            sleep_out_count_add(&g_ebike_status.sleep);
            if (get_sleep_out_count(&g_ebike_status.sleep) >= QUIT_LOW_POWER_TIME)
            {
                usr_quit_low_power();                                            // 退出低功耗
                set_ebike_state_info(&g_ebike_status,WORK_STATUS,V_STOP);//退出低功耗状态
                set_ebike_rules(&g_ebike_status,EBIKE_STATUS);
                usr_delay_ms(60 * LOW_POWER_TASK_DELAY_1S);                      // 等待60秒,各线程更新参数
                if (get_ebike_state_info(&g_ebike_status, ACC_STATUS) == V_OFF) // 如果无启动，则再次进入低功耗
                {
                    set_ebike_rules(&g_ebike_status,EBIKE_STATUS);
                    set_ebike_state_info(&g_ebike_status,WORK_STATUS,V_SLEEP);//进入低功耗状态
                    usr_enter_low_power();                                       // 进入低功耗
                }  
            }
        }
        usr_delay_s(LOW_POWER_TASK_DELAY_1S);
    }
}
/**
 * @brief weel warn process
 *
 * @author zcj (605607217@qq.com)
 * @date 2023-11-06
 */

void publish_task(void *pv)
{
    while (get_mqtt_status(&g_dev_lte) != MQTT_STATE_READY)
    {
        LUAT_DEBUG_PRINT("publish_task wait mqtt_status ready");
        luat_rtos_task_sleep(1000);
    }

    uint16_t heart_packet_times_cnt = 0;
    uint16_t normal_packet_times_cnt = 0;
    uint8_t  online_packet_times_cnt = 0;
    uint32_t val, val2;
    while (1)
	{

        if((get_ebike_state_info(&g_ebike_status, MOVE_FLAG) == V_ON)||(get_gnss_speed(&g_ebike_status.gnss)>=10)) // 运动状态20秒钟上报
        {
            if ((normal_packet_times_cnt >= g_dev_info->info.move_up_cycle))
            {
                luat_rtos_message_send(message_event_deal_task_handle, CASE_TASK_ON_REPORT, (void *)NULL);
                normal_packet_times_cnt = 0;
            }           
        }
        else if(normal_packet_times_cnt >= g_dev_info->info.stop_up_cycle)//静止状态10分钟上报
        {
            luat_rtos_message_send(message_event_deal_task_handle, CASE_TASK_ON_REPORT, (void *)NULL);
            normal_packet_times_cnt = 0;
        }
		if (heart_packet_times_cnt >= HEART_REPORT_TIME) // 心跳包3分钟上报
        {
			luat_rtos_message_send(message_event_deal_task_handle, CASE_TASK_PING, (void *)NULL);
			heart_packet_times_cnt = 0;
		}
        if ((online_packet_times_cnt>30)&&(g_dev_info->info.online_flag==true))//上线数据包，重复间隔30秒上报
        {
            online_packet_times_cnt=0;
            luat_rtos_message_send(message_event_deal_task_handle, CASE_TASK_ON_LINE, (void *)NULL);            
        }
        
        luat_adc_read(BAT_DET_CHECK, &val, &val2);
        set_ebike_vin(&g_ebike_status, (val2*108+1250000)/1000);
        if ((get_ebike_vin(&g_ebike_status)>=42000)&&(get_ebike_state_info(&g_ebike_status,POWER_STATUS)!=V_ON))
        {
            set_ebike_state_info(&g_ebike_status,POWER_STATUS,V_ON);  
            set_ebike_rules(&g_ebike_status,LOW_SOC);                 
        }
        else if ((get_ebike_vin(&g_ebike_status)<42000)&&(get_ebike_state_info(&g_ebike_status,POWER_STATUS)!=V_OFF))
        {
            set_ebike_state_info(&g_ebike_status,POWER_STATUS,V_OFF);
            set_ebike_rules(&g_ebike_status,LOW_SOC);
        }
        if (beep_player.play_num>0)
        {
            if(beep_player.play_f==false)
            {
                v_beep_ctrl(true);
                beep_player.play_f=true;
            }
            else 
            {
                v_beep_ctrl(false);
                beep_player.play_f=false;
                beep_player.play_num--;                
            }           				
        }
        else if (beep_player.play_num==0) 
        {
            v_beep_ctrl(false);
            beep_player.play_f=false;
            beep_player.play_num=-1;
            /*7.开启下一次轮动报警*/
             set_ebike_state_info(&g_ebike_status, ANTI_THEFT, V_OFF);
        }
        if(get_ebike_rules(&g_ebike_status)>0)//触发事件上报
        {
            luat_rtos_message_send(message_event_deal_task_handle, CASE_TASK_ON_CHANG, (void *)NULL);
        }
        luat_adc_read(LUAT_ADC_CH_CPU, &val, &val2);
        set_ebike_temp(&g_ebike_status,(uint8_t)val2);
		usr_delay_s(1);
		heart_packet_times_cnt++;
        online_packet_times_cnt++;
		normal_packet_times_cnt++;
	}
}
/**
 * @brief msg event deal
 *
 * @param param
 * @author zcj (605607217@qq.com)
 * @date 2023-11-06
 */
static void message_event_deal_task(void *param)
{
    CASE_TASK_MSG id;
    void *data = NULL;

    luat_rtos_task_create(&publish_task_handle, 1024 * 2, 20, "publish_task_handle", publish_task, NULL, 10);

    while (1)

    {
        if (0 == luat_rtos_message_recv(message_event_deal_task_handle, (uint32_t)&id, (void **)&data, LUAT_WAIT_FOREVER))
        {
            switch (id)
            {
                case CASE_TASK_PING:                    //心跳包
                    usr_log("CASE_TASK_PING_MSG");
                    heart_pkg_func();
                    data_mode_count_add(&gsm_work_led);
                    break;
                case CASE_TASK_ON_CHANG:                    //事件通知
                    on_change_func();
                    data_mode_count_add(&gsm_work_led);
                    break;
                case CASE_TASK_ON_REPORT:                   //属性上报
                    on_reoprt_func();
                    data_mode_count_add(&gsm_work_led);
                    break;
                case CASE_TASK_ON_ALARM:                    //设防状态下轮动报警
                    /*4.语音播报三次*/
                    beep_player.play_num=3;       
                    set_ebike_rules(&g_ebike_status,WHEEL_STATUS);
                    break;
                case CASE_TASK_ON_CONTROL:
                    on_control_func();//获取设备参数响应上报
                    data_mode_count_add(&gsm_work_led);
                    break;
                case CASE_TASK_ON_LINE: //上线通知                    
                    on_line_func();
                    data_mode_count_add(&gsm_work_led);
                    break;
                default:
                    break;
            }
        }
    }
}

/**
 * @brief wheel event deal
 *
 * @param param
 * @author zcj (605607217@qq.com)
 * @date 2023-11-06
 */




/**
 * @brief gps event deal
 *
 * @param param
 * @author zcj (605607217@qq.com)
 * @date 2023-11-06
 */
static void gps_event_deal_task(void *param)
{
    uint32_t id;
    DEV_GNSS_T *gnss = NULL;
    bool one_flag=false;
    double lng1 = 0;
    double lat1 = 0;
    double lng2 = 0; 
    double lat2 = 0;
    double distance;                               // 结果，包括距离及方向
    while (1)
    {
        if (0 == luat_rtos_message_recv(gps_event_deal_task_handle, &id, (void **)&gnss, LUAT_WAIT_FOREVER))
        {
            luat_rtos_mutex_lock(g_ebike_status.mutex, LUAT_WAIT_FOREVER);            
            if((get_gnss_gps_status(&g_ebike_status.gnss)==1)||(get_gnss_fixMode(&g_ebike_status.gnss)!=0))//定位有效
            {
                if (get_ebike_state_info(&g_ebike_status,GPS_STATUS)!=V_ON)
                {
                    set_ebike_state_info(&g_ebike_status,GPS_STATUS,V_ON);
                    work_led_mode_switch(&gnss_work_led, MODE_DATA);
                    set_ebike_rules(&g_ebike_status,GNSS_STATUS);
                }     
                
                data_mode_count_add(&gnss_work_led);//每收到一条GNSS数据，蓝灯闪烁一次。
                if (get_ebike_state_info(&g_ebike_status, MOVE_FLAG)==V_ON)//在骑行，计算里程并累加
                {
                    if ((lat1==0)&&(lng1==0))//第一次
                    {
                        lng1=get_gnss_lon(&g_ebike_status.gnss);//起点
                        lat1=get_gnss_lat(&g_ebike_status.gnss);//起点
                    }
                    else
                    {
                        lng2=get_gnss_lon(&g_ebike_status.gnss);//终点
                        lat2=get_gnss_lat(&g_ebike_status.gnss);//终点
                        distance=gps_cacl(lng1, lat1,lng2,lat2);//计算   
                        gnss->mileage=distance*1000;//当前里程
                        gnss->Accumulated_mileage+=gnss->mileage;//累计里程  
                        lat1=lat2;//当前终点作为下一次起点
                        lng1=lng2;//当前终点作为下一次起点                   
                    }                   
                }
            }  
            else if((get_gnss_gps_status(&g_ebike_status.gnss)==0)||(get_gnss_fixMode(&g_ebike_status.gnss)==0))
            {
                if (get_ebike_state_info(&g_ebike_status,GPS_STATUS)!=V_OFF)
                {
                    set_ebike_state_info(&g_ebike_status,GPS_STATUS,V_OFF);
                    work_led_mode_switch(&gnss_work_led, MODE_INIT);
                    set_ebike_rules(&g_ebike_status,GNSS_STATUS);
                }                   
            }            
            memcpy(&g_ebike_status.gnss, gnss, sizeof(DEV_GNSS_T));    
            luat_rtos_mutex_unlock(g_ebike_status.mutex);
            if (gnss != NULL)
            free(gnss);
        }
    }
}

/**
 * @brief ota event deal
 *  轮不动、设防、无订单下进行
 * @param param
 * @author zcj (605607217@qq.com)
 * @date 2023-11-06
 */
// static void ota_event_deal_task(void *param)
// {
//     luat_rtos_mutex_create(&g_ota.mutex);
//     while (1)
//     {
//         if (get_ebike_state_info(&g_ebike_status, MOVE_FLAG) == V_OFF &&
//             get_ebike_state_info(&g_ebike_status, CLCK_STATUS) == V_ON &&
//             get_ebike_state_info(&g_ebike_status, WORK_STATUS) == V_OFF &&
//             get_ebike_state_info(&g_ebike_status, BIKE_LOCKED) == V_OFF)
//         {
//             if (get_ota_module(&g_ota, MODULE_4G) == MODULE_4G && get_ota_action(&g_ota) == ACTION_FREE)
//             {
//                 set_ota_action(&g_ota, ACTION_RUNNING);
//                 fota_start_task(MODULE_4G);
//             }
//             else if (get_ota_module(&g_ota, MODULE_JL) == MODULE_JL && (get_ota_action(&g_ota) == ACTION_FREE))
//             {
//                 set_ota_action(&g_ota, ACTION_RUNNING);
//                 fota_start_task(MODULE_JL);
//             }
//             else if (get_ota_module(&g_ota, MODULE_AUDIO) == MODULE_AUDIO && (get_ota_action(&g_ota) == ACTION_FREE))
//             {
//                 set_ota_action(&g_ota, ACTION_RUNNING);
//                 if (get_dev_info_audio_exist(g_dev_info) == AUDIO_NOT_EXIST)
//                 {
//                     uint8_t ret = usr_update_audio(g_ota.host_audio, g_ota.url_audio);
//                     if (ret == true)
//                     {
//                         set_dev_info_audio_exist(g_dev_info, AUDIO_EXIST);
//                         mqtt_server_flash_update(g_dev_info);
//                         on_reoprt_func();
//                     }
//                 }
//                 set_ota_action(&g_ota, ACTION_FREE);
//             }
//         }
//         usr_delay_s(10);
//     }
// }








/**
 * @brief app event deal
 *
 * @author zcj (605607217@qq.com)
 * @date 2023-11-06
 */
void app_event_deal_init(void)
{
    /**
     *  消息事件处理
     */
    luat_rtos_task_create(&message_event_deal_task_handle, 1024 * 6, 30, "message_event_deal_task", message_event_deal_task, NULL, 10);
    /**
     *  轮动事件处理
     */
    luat_rtos_task_create(&wheel_event_deal_task_handle, 1024 * 2, 30, "wheel_event_deal_task", wheel_event_deal_task, NULL, NULL);
    /**
     *  gps事件处理
     */
    luat_rtos_task_create(&gps_event_deal_task_handle, 1024 * 2, 20, "gps_event_deal_task", gps_event_deal_task, NULL, 20);
    /**
     *  睡眠事件处理
     */
    luat_rtos_task_create(&sleep_event_deal_task_handle, 1024 * 2, 20, "sleep_task_handle", sleep_event_deal_task, NULL, NULL);
    /**
     *  OTA事件处理
     */
    //luat_rtos_task_create(&ota_event_deal_task_handle, 1024 * 2, 50, "ota_event_deal_task", ota_event_deal_task, NULL, NULL);   
    
}
